<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="问卷标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入问卷标题" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="问卷状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="问卷状态" clearable style="width: 240px">
          <el-option label="草稿" value="draft" />
          <el-option label="已发布" value="published" />
          <el-option label="已关闭" value="closed" />
        </el-select>+
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['questionnaire:questionnaire:add']">新增问卷</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single || isSelectedClosed" @click="handleUpdate" v-hasPermi="['questionnaire:questionnaire:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['questionnaire:questionnaire:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="View" :disabled="multiple" @click="handleView" v-hasPermi="['questionnaire:questionnaire:query']">预览</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="DataAnalysis" :disabled="multiple" @click="handleStats" v-hasPermi="['questionnaire:questionnaire:stats']">统计</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionnaireList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" :selectable="isSelectable" />
      <el-table-column label="问卷编号" align="center" key="id" prop="id" v-if="columns[0].visible" width="80" />
      <el-table-column label="问卷标题" align="center" key="title" prop="title" v-if="columns[1].visible" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="问卷描述" align="center" key="description" prop="description" v-if="columns[2].visible" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="状态" align="center" key="status" v-if="columns[3].visible" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="题目数量" align="center" key="questionCount" v-if="columns[4].visible" width="100">
        <template #default="scope">
          {{ scope.row.questionCount || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="答卷数量" align="center" key="answerCount" v-if="columns[5].visible" width="100">
        <template #default="scope">
          {{ scope.row.answerCount || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
            <el-tooltip content="修改" placement="top" v-if="scope.row.status !== 'closed'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['questionnaire:questionnaire:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['questionnaire:questionnaire:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="预览" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['questionnaire:questionnaire:query']"></el-button>
            </el-tooltip>
            <el-tooltip content="统计" placement="top">
              <el-button link type="primary" icon="DataAnalysis" @click="handleStats(scope.row)" v-hasPermi="['questionnaire:questionnaire:stats']"></el-button>
            </el-tooltip>
            <el-dropdown @command="cmd => handleCommand(cmd, scope.row)" v-if="scope.row.status === 'draft'">
              <el-button link type="primary" icon="MoreFilled" :loading="loadingPublish"></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="publish" icon="Promotion" :disabled="scope.row.status !== 'draft'">发布问卷</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-dropdown @command="cmd => handleCommand(cmd, scope.row)" v-if="scope.row.status === 'published'">
              <el-button link type="primary" icon="MoreFilled"></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="close" icon="Lock">关闭问卷</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改问卷对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form :model="form" :rules="rules" ref="questionnaireRef" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="问卷标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入问卷标题" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="问卷描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入问卷描述" :rows="3" maxlength="500" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="草稿" value="draft" />
                <el-option label="已发布" value="published" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 问卷预览对话框 -->
    <el-dialog title="问卷预览" v-model="previewOpen" width="900px" append-to-body>
      <div class="questionnaire-preview">
        <div class="preview-header">
          <h2 class="preview-title">{{ previewData.title || '未命名问卷' }}</h2>
          <p class="preview-description">{{ previewData.description || '暂无描述' }}</p>
          <div class="preview-meta">
            <el-tag :type="getStatusType(previewData.status)" size="small">
              {{ getStatusText(previewData.status) }}
            </el-tag>
            <span class="question-count">共 {{ (previewData.questions || []).length }} 道题目</span>
          </div>
        </div>
        
        <div class="preview-questions">
          <div v-for="(question, index) in (previewData.questions || [])" :key="question.id || index" class="preview-question-item">
            <div class="question-header">
              <span class="question-number">{{ index + 1 }}</span>
              <span class="question-title">{{ question.content || '未命名题目' }}</span>
              <el-tag v-if="question.required" type="danger" size="small" class="required-tag">必填</el-tag>
              <el-tag type="info" size="small" class="type-tag">
                {{ getQuestionTypeText(question.questionType) }}
              </el-tag>
            </div>
            
            <div class="question-content">
              <!-- 单选题 -->
              <div v-if="question.questionType === 'single'" class="options-container">
                <el-radio-group v-model="previewAnswers[question.id]" disabled>
                  <div v-for="option in (question.options || [])" :key="option.id || option.optionValue" class="option-item">
                    <el-radio :value="option.optionValue">
                      {{ option.optionLabel }}
                    </el-radio>
                  </div>
                </el-radio-group>
              </div>
              
              <!-- 多选题 -->
              <div v-else-if="question.questionType === 'multiple'" class="options-container">
                <el-checkbox-group v-model="previewAnswers[question.id]" disabled>
                  <div v-for="option in (question.options || [])" :key="option.id || option.optionValue" class="option-item">
                    <el-checkbox :value="option.optionValue">
                      {{ option.optionLabel }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
              
              <!-- 文本题 -->
              <div v-else-if="question.questionType === 'text'" class="text-container">
                <el-input 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入您的答案" 
                  disabled
                  class="text-input"
                />
              </div>
              
              <!-- 无选项时显示提示（仅对单选题和多选题） -->
              <div v-if="(question.questionType === 'single' || question.questionType === 'multiple') && (!question.options || question.options.length === 0)" class="no-options">
                <el-empty description="暂无选项" :image-size="60" />
              </div>
            </div>
          </div>
          
          <div v-if="!previewData.questions || previewData.questions.length === 0" class="no-questions">
            <el-empty description="该问卷暂无题目" :image-size="100" />
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewOpen = false">关闭</el-button>
          <el-button type="primary" @click="handleFillQuestionnaire" v-if="previewData.status === 'published'">
            填写问卷
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="QnQuestionnaireIndex">
import { ref, reactive, toRefs, computed, getCurrentInstance } from 'vue'
import { listQuestionnaire, getQuestionnaire, delQuestionnaire, addQuestionnaire, updateQuestionnaire, publishQuestionnaire, closeQuestionnaire, getQuestionList, listOptions } from "@/api/questionnaire"

const { proxy } = getCurrentInstance()

const questionnaireList = ref([])
const open = ref(false)
const previewOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])
const previewData = ref({})
const previewAnswers = ref({})
const saving = ref(false)
const loadingPublish = ref(false)

// 列显隐信息
const columns = ref([
  { key: 0, label: `问卷编号`, visible: true },
  { key: 1, label: `问卷标题`, visible: true },
  { key: 2, label: `问卷描述`, visible: true },
  { key: 3, label: `状态`, visible: true },
  { key: 4, label: `题目数量`, visible: true },
  { key: 5, label: `答卷数量`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    status: undefined
  },
  rules: {
    title: [{ required: true, message: "问卷标题不能为空", trigger: "blur" }],
    description: [{ required: true, message: "问卷描述不能为空", trigger: "blur" }]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 计算属性：判断选中的问卷是否包含已关闭状态的问卷
const isSelectedClosed = computed(() => {
  if (ids.value.length === 0) return false
  // 从当前选中的问卷列表中查找是否有已关闭状态的问卷
  return questionnaireList.value.some(item => 
    ids.value.includes(item.id) && item.status === 'closed'
  )
})

/** 查询问卷列表 */
function getList() {
  loading.value = true
  listQuestionnaire(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false
    questionnaireList.value = res.rows
    total.value = res.total
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 判断行是否可选 */
function isSelectable(row) {
  // 已关闭的问卷不可选中
  return row.status !== 'closed'
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加问卷"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getQuestionnaire(id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改问卷"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["questionnaireRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateQuestionnaire(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addQuestionnaire(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const questionnaireIds = row.id || ids.value
  proxy.$modal.confirm('是否确认删除问卷编号为"' + questionnaireIds + '"的数据项？').then(function () {
    return delQuestionnaire(questionnaireIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 预览按钮操作 */
function handleView(row) {
  // 检查row是否是事件对象（从工具栏按钮调用）
  const isEvent = row && row.type === 'click'
  
  // 如果是事件对象或者row没有id属性，则使用选中的第一个问卷
  const id = (isEvent || !row || !row.id) ? (ids.value.length > 0 ? ids.value[0] : null) : row.id
  
  if (!id) {
    proxy.$modal.msgError("请先选择一个问卷")
    return
  }
  
  console.log('预览问卷ID:', id)
  
  getQuestionnaire(id).then(response => {
    console.log('问卷基本信息:', response.data)
    previewData.value = response.data
    return getQuestionList(id)
  }).then(questionResponse => {
    console.log('题目列表响应:', questionResponse)
    const questions = Array.isArray(questionResponse.rows) ? questionResponse.rows : []
    console.log('题目列表:', questions)
    
    // 检查题目是否已经包含选项信息
    const questionsWithOptions = questions.map(question => {
      console.log('处理题目:', question)
      console.log('题目选项:', question.options)
      
      // 如果题目已经有选项信息，直接使用
      if (question.options && Array.isArray(question.options) && question.options.length > 0) {
        console.log('题目已有选项，直接使用:', question.options)
        return question
      }
      
      // 如果没有选项信息，则单独获取
      if (question.questionType !== 'text') {
        return listOptions(question.id).then(optionResponse => {
          console.log('获取到的选项:', optionResponse)
          // 注意：listOptions返回的是数组，不是{rows: []}格式
          const options = Array.isArray(optionResponse) ? optionResponse : []
          console.log('处理后的选项:', options)
          console.log('选项详情:')
          options.forEach((opt, i) => {
            console.log(`选项${i+1}:`, opt)
          })
          // 使用Vue的响应式API确保数据是响应式的
          question.options = [...options]
          console.log('设置选项后的题目:', question)
          return question
        }).catch(() => {
          console.log('获取选项失败，设置为空数组')
          question.options = []
          return question
        })
      } else {
        question.options = []
        return Promise.resolve(question)
      }
    })
    
    // 检查是否所有题目都已经有选项信息
    const allHaveOptions = questionsWithOptions.every(q => !(q instanceof Promise))
    if (allHaveOptions) {
      console.log('所有题目都有选项，直接显示')
      previewData.value.questions = questionsWithOptions
      previewOpen.value = true
      return Promise.resolve()
    } else {
      console.log('部分题目需要获取选项，等待Promise完成')
      return Promise.all(questionsWithOptions)
    }
  }).then(questionsWithOptions => {
    if (questionsWithOptions) {
      console.log('最终题目列表:', questionsWithOptions)
      console.log('最终题目列表详情:')
      questionsWithOptions.forEach((q, i) => {
        console.log(`题目${i+1}:`, q)
        console.log(`题目${i+1}选项:`, q.options)
      })
      previewData.value.questions = questionsWithOptions
      console.log('设置到previewData的questions:', previewData.value.questions)
      previewOpen.value = true
    }
  }).catch(error => {
    console.error('获取问卷预览信息失败:', error)
    proxy.$modal.msgError("获取问卷预览信息失败")
  })
}

/** 统计按钮操作 */
function handleStats(row) {
  // 检查row是否是事件对象（从工具栏按钮调用）
  const isEvent = row && row.type === 'click'
  
  // 如果是事件对象或者row没有id属性，则使用选中的第一个问卷
  const id = (isEvent || !row || !row.id) ? (ids.value.length > 0 ? ids.value[0] : null) : row.id
  
  if (!id) {
    proxy.$modal.msgError("请先选择一个问卷")
    return
  }
  
  proxy.$router.push(`/questionnaire/stats/${id}`)
}

/** 更多操作 */
async function handleCommand(command, row) {
  let questionnaireId = row.id
  const questionnaireTitle = row.title || '未命名问卷'
  // 必须有ID
  if (!questionnaireId) {
    proxy.$modal.msgError("问卷ID不能为空")
    return
  }
  // 发布
  if (command === 'publish') {
    if (row.status !== 'draft') {
      proxy.$modal.msgError('只有草稿状态的问卷才能发布')
      return
    }
    if (loadingPublish.value) return
    loadingPublish.value = true
    proxy.$modal.confirm('确认要发布问卷"' + questionnaireTitle + '"吗?').then(function () {
      return publishQuestionnaire(questionnaireId)
    }).then(() => {
      proxy.$modal.msgSuccess("发布成功")
    }).catch((error) => {
      proxy.$modal.msgError("发布失败：" + (error.message || '未知错误'))
    }).finally(() => {
      loadingPublish.value = false
      getList()
    })
  }
  // 关闭
  if (command === 'close') {
    if (row.status !== 'published') {
      proxy.$modal.msgError('只有已发布状态的问卷才能关闭')
      return
    }
    if (loadingPublish.value) return
    loadingPublish.value = true
    proxy.$modal.confirm('确认要关闭问卷"' + questionnaireTitle + '"吗?').then(function () {
      return closeQuestionnaire(questionnaireId)
    }).then(() => {
      proxy.$modal.msgSuccess("关闭成功")
    }).catch((error) => {
      proxy.$modal.msgError("关闭失败：" + (error.message || '未知错误'))
    }).finally(() => {
      loadingPublish.value = false
      getList()
    })
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    title: null,
    description: null,
    status: "draft"
  }
  proxy.resetForm("questionnaireRef")
}

/** 获取状态类型 */
function getStatusType(status) {
  switch (status) {
    case 'draft': return 'info'
    case 'published': return 'success'
    case 'closed': return 'danger'
    default: return 'info'
  }
}

/** 获取状态文本 */
function getStatusText(status) {
  switch (status) {
    case 'draft': return '草稿'
    case 'published': return '已发布'
    case 'closed': return '已关闭'
    default: return '未知'
  }
}

/** 获取题目类型文本 */
function getQuestionTypeText(questionType) {
  switch (questionType) {
    case 'single': return '单选题'
    case 'multiple': return '多选题'
    case 'text': return '文本题'
    default: return '未知类型'
  }
}

/** 填写问卷 */
function handleFillQuestionnaire() {
  if (previewData.value.id) {
    proxy.$router.push(`/questionnaire/fill/${previewData.value.id}`)
    previewOpen.value = false
  }
}

getList()
</script>

<style scoped>
.questionnaire-preview {
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.preview-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

.preview-title {
  color: #303133;
  margin-bottom: 10px;
  font-size: 24px;
  font-weight: bold;
}

.preview-description {
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.6;
  font-size: 14px;
}

.preview-meta {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.question-count {
  color: #909399;
  font-size: 12px;
}

.preview-questions {
  margin-top: 20px;
}

.preview-question-item {
  margin-bottom: 25px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s;
}

.preview-question-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}

.question-number {
  background-color: #409eff;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.question-title {
  flex: 1;
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}

.required-tag {
  margin-left: auto;
}

.type-tag {
  margin-left: 5px;
}

.question-content {
  margin-left: 34px;
}

.options-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  padding: 8px 12px;
  border-radius: 4px;
  background-color: white;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.option-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.text-container {
  margin-top: 10px;
}

.text-input {
  width: 100%;
}

.no-options {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.no-questions {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}
</style> 